package org.example.translation;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.SAXReader;

import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Dom4jDocUtil {

    public static @Nullable StringsXMLData convertDocumentToData(String xmlFolder) {
        return convertDocumentToData(xmlFolder,new DefaultCountryTransformer());
    }
    /**
     * Dom4j的Document对象转StringsXMLData对象
     * @param xmlFolder xml文件路径。只接受到values-xx级别
     * @param transformer 判断国家
     * @return
     */
    public static @Nullable StringsXMLData convertDocumentToData(String xmlFolder, StringFolderCountryTransformer transformer){
        Map<String, Element> sourceKV = new HashMap<>();
        Map<String, List<?>> sourceArrayKV = new HashMap<>();
        Map<String,Element> sourceArray = new HashMap<>();

        try {
            //源文件的数据
            Document sourceDocument = new SAXReader().read(xmlFolder+"\\strings.xml");
            Element sourceDocumentRootElement = sourceDocument.getRootElement();
            List<?> elementString = sourceDocumentRootElement.elements("string");
            List<?> stringArrayElement = sourceDocumentRootElement.elements("string-array");

            for (Object o : elementString) {
                Element element = (Element) o;
                String key = element.attribute("name").getValue();
                sourceKV.put(key, element);
            }

            for (Object o : stringArrayElement) {
                Element element = (Element) o;
                String key = element.attribute("name").getValue();
                sourceArrayKV.put(key, element.elements("item"));
                sourceArray.put(key,element);
            }
            return new StringsXMLData()
                    .setSourceKV(sourceKV)
                    .setSourceArrayKV(sourceArrayKV)
                    .setSourceDocument(sourceDocument)
                    .setSourceArray(sourceArray)
                    .setCountry(transformer.apply(xmlFolder));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建一个新的document对象并填入StringsXMLData返回
     * @return StringsXMLData
     */
    public static StringsXMLData createAndroidStringXmlDocument(){
        StringsXMLData stringsXMLData = new StringsXMLData();
        DOMElement rootElement = new DOMElement("resources");
        Document document = new DOMDocument(rootElement);
        stringsXMLData.setSourceDocument(document);
        return stringsXMLData;
    }
}
